﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using util;
using System.IO;
namespace WebApplication1.studentUser
{
    public partial class Notice : System.Web.UI.Page
    {
        private static string url;
        protected void Page_Load(object sender, EventArgs e)
        {

            String sql = "SELECT title,publishDate,publisher,content,filename FROM notice where publishDate = '" + Application["publishDate"] + "';";
            DataTable table = MySqlHelper.GetDataTable(sql);
            title.Text = table.Rows[0]["title"].ToString();
            content.Text = table.Rows[0]["content"].ToString();
            publisher.Text = table.Rows[0]["publisher"].ToString();
            publishDate.Text = table.Rows[0]["publishDate"].ToString();
            //sender.CommandArgument = table.Rows[0]["filename"].ToString();
            string str = table.Rows[0]["filename"].ToString();
            string[] arr = str.Split('\\');
            foreach (string s in arr)
            {
                lbtnDownLoad.Text = s;
            }
            String filename = table.Rows[0]["filename"].ToString();
            String filePath = Server.MapPath("~/UploadFiles/");
            url = filePath + filename;
            url = url.ToString().Replace("\\", "\\\\");
        }
         
    protected void lbtnDownLoad_Command(object sender, CommandEventArgs e)
    {
            Response.Write("<script>alert('" + url + "');</script>");
            // 定义文件名  
             string fileName = "";
             // 获取文件在服务器的地址  

             // 判断传输地址是否为空  
             if (url == "")
             {
                 // 提示“该文件暂不提供下载”  
                 Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script defer>alert('该文件暂不提供下载！');</script>");
                 return;
             }
             // 判断获取的是否为地址，而非文件名  
             if (url.IndexOf("\\") > -1)
             {
                 // 获取文件名  
                 fileName = url.Substring(url.LastIndexOf("\\") + 1);
             }
             else
             {
                 // url为文件名时，直接获取文件名  
                 fileName = url;
             }
             // 以字符流的方式下载文件  
             FileStream fileStream = new FileStream(@url, FileMode.Open);
             byte[] bytes = new byte[(int)fileStream.Length];
             fileStream.Read(bytes, 0, bytes.Length);
             fileStream.Close();
             Response.ContentType = "application/octet-stream";

             // 通知浏览器下载 
             Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
             Response.BinaryWrite(bytes);
             Response.Flush();
             Response.End();
        }

}
}